package com.xnew.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.Date;

/**
 * <p>
 * Title: FileFtpUtil.java
 * </p>
 * <p>
 * Copyright: Copyright (c) 2019
 * </p>
 * <p>
 * Company: www.xnewtech.com
 * </p>
 *
 * @author yangcd
 * @version 1.0
 * @date 2022年5月11日 下午7:24:33
 */
@Component
@Configuration
public class FileFtpUtil {

//    @Value("${ftp.host}")
//    private String ftpHost = "8.142.15.238";
//    @Value("${ftp.port}")
//    private String ftpPort = "21";
//    @Value("${ftp.username}")
//    private String username = "user";
//    @Value("${ftp.password}")
//    private String password = "user123";
//    @Value("${file.destPath}")
//    private String destPath = "/www/wwwroot/user";

    @Value("${ftp.host}")
    private String ftpHost;
    @Value("${ftp.port}")
    private String ftpPort;
    @Value("${ftp.username}")
    private String username;
    @Value("${ftp.password}")
    private String password;
    @Value("${ftp.destPath}")
    private String destPath;

    @Value("${filePath.mountPath}")
    private String mountPath;






    /**
     * 上传文件
     *
     * @param content
     * @return 格式：{"fileID":"....","filePath":"..."}
     * @throws Exception
     */
    public String uploadFile(MultipartFile content) throws Exception {
        String fileName = content.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        File file = transferToFile(content);
        return this.uploadFile(file, destPath);
    }

    public File transferToFile(MultipartFile multipartFile) {
//        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 上传文件
     *
     * @param file
     * @return 格式：{"fileID":"....","filePath":"..."}
     * @throws Exception
     */
    public String uploadFile(File file, String path) throws Exception {
        Ftp ftp = new Ftp(ftpHost, Integer.parseInt(ftpPort), username, password, CharsetUtil.CHARSET_UTF_8, FtpMode.Passive);
        String fileName = buildFileName(file);
        String filePath = path + "/"+ DateUtils.dateTimeToDateString(new Date()) + "/";
        boolean isTrue = ftp.upload(filePath,fileName, file);

        System.out.println(isTrue);
        JSONObject json = new JSONObject();
        StringBuilder strBur = new StringBuilder(filePath);
        strBur.append(fileName);
        json.put("filePath", strBur);
        return JSON.toJSONString(json);

    }

    /**
     * 上传文件
     *
     * @param file
     * @param fileName
     * @throws Exception
     */
    public  String uploadFile(MultipartFile file, String fileName) throws Exception {

        //目标路径
        File uploadfile = new File(mountPath + File.separator + DateUtils.dateTimeToDateString(new Date()));
        //如果文件目录不存在，就执行创建
        if(!uploadfile.isDirectory()){
            uploadfile.mkdirs();
        }

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHss");
//        //目标文件名称
//        String targetName =sdf.format(new Date()) + "_"+fileName;
//        //创建目标文件
//        String targetFilePath = destPath + targetName;
        String filePath = mountPath + File.separator + DateUtils.dateTimeToDateString(new Date()) + File.separator+ this.buildFileName(fileName);
        File targetFile = new File(filePath);
        FileOutputStream fos = new FileOutputStream(targetFile);
        //读取本地文件
        InputStream stream = file.getInputStream();

        //写入目标文件
        byte[] buffer = new byte[1024*1024];
        int byteRead;
        while((byteRead = stream.read(buffer)) != -1){
            fos.write(buffer, 0, byteRead);
            fos.flush();
        }
        fos.close();
        stream.close();
        //       targetFilePath = AesEncryptUtils.encrypt(targetFilePath, Constant.AES_KEY);
        JSONObject json = new JSONObject();
        json.put("filePath", filePath);
        return JSON.toJSONString(json);
    }

    public String buildFileName(File file){
        if(file == null) {
            return String.valueOf(System.nanoTime());
        }
        String filename = file.getName();
        if(filename.lastIndexOf(".") == -1){
            return String.valueOf(System.nanoTime());//⽂件没有后缀名的情况
        }
        //此时返回的是带有 . 的后缀名，
        return System.nanoTime() + filename.substring(filename.lastIndexOf("."));
    }

    public String buildFileName(String  filename){
        if(filename.lastIndexOf(".") == -1){
            return String.valueOf(System.nanoTime());//⽂件没有后缀名的情况
        }
        //此时返回的是带有 . 的后缀名，
        return System.nanoTime() + filename.substring(filename.lastIndexOf("."));
    }

    /**
     * 下载文件
     *
     * @param filePath 待下载文件的路径
     */
    public InputStream downloadFile(String filePath) throws IOException, FtpProtocolException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(ftpHost, Integer.parseInt(ftpPort));
        FtpClient ftpClient = FtpClient.create(inetSocketAddress);
        ftpClient.login(username, password.toCharArray());

        //进入远程目录
        InputStream in = ftpClient.getFileStream(filePath);
//        File file = new File(filePath);
//        InputStream in =  new FileInputStream(file);
        return in;
    }


    public static void main(String[] args) throws Exception {

//
//        String path = "D:\\VIPWork\\会员2.0进度.xlsx";
//        File f1 = new File(path);
//        System.out.println(new FileFtpUtil().uploadFile(f1));
    }

}
